package com.bfly.core.config;

import com.bfly.core.context.ContextUtil;
import com.bfly.mall.admin.entity.Admin;
import com.bfly.mall.system.entity.SysLog;
import com.bfly.mall.system.service.ISysLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 系统日志AOP配置
 *
 * @author 长沙商脉科技有限公司
 * @date 2019/6/26 18:00
 */
@Aspect
@Component
public class SysLogsAop extends AbstractLogsAop {

    @Autowired
    private ISysLogService sysLogService;

    /**
     * 定义日志切入点方法
     *
     * @author 长沙商脉科技有限公司
     * @date 2019/6/27 17:22
     */
    @Pointcut("execution(* com.bfly..*.controller..*.*(..))")
    public void pointcut() {
    }

    /**
     * 目标对象方法调用之前执行
     *
     * @author 长沙商脉科技有限公司
     * @date 2019/6/27 17:22
     */
    @Before("pointcut()")
    public void beforeRequest(JoinPoint joinPoint) {
        super.beforeRequest(joinPoint);
    }

    /**
     * 目标对象方法抛出异常后执行
     *
     * @author 长沙商脉科技有限公司
     * @date 2019/6/27 17:23
     */
    @AfterThrowing(pointcut = "pointcut()", throwing = "throwable")
    public void afterThrowingRequest(JoinPoint joinPoint, Throwable throwable) {
        super.afterThrowingRequest(joinPoint, throwable);
    }

    @Override
    void saveLog(String ip, String url, String title, String content, boolean success) {
        final Admin admin = ContextUtil.getLoginAdmin();
        SysLog log = new SysLog();
        log.setUserName(admin==null?"":admin.getUserName());
        log.setIp(ip);
        log.setUrl(url);
        log.setTitle(title);
        log.setContent(content);
        log.setSuccess(success);
        log.setTime(new Date());
        sysLogService.save(log);
    }
}
